<template>
  <div style="margin-top: 30px"></div>
  <a-row>
    <a-col :span="14" >
      <a-row>
        <a-col :span="10" :offset="1">
          <a-input-search
              style="width: 280px"
              v-model:value="searchValue"
              placeholder="请输入文档名称"
              :loading="searchLoading"
              enter-button
              size="large"
              @search="search"
          ></a-input-search>
        </a-col>
        <a-col :span="5">
          <a-button type="primary" size="large" @click="add">新增</a-button>
        </a-col>
      </a-row>
      <a-table :columns="columns"
               :data-source="docs"
               :row-key="record => record.id"
               :loading="tableLoading"
               :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <img class="cover" :src="record.cover" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" @click="edit(record)">编辑</a-button>
              <a-popconfirm title="确认要删除吗？" @confirm="remove(record.id)">
                <template #icon><question-circle-outlined style="color: red" /></template>
                <a-button type="primary" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-col>
    <a-col :span="8" :offset="1" style="background-color: #fff;">
      <!-- 新增 -->
      <a-row style="background-color: #fff; padding: 25px">
        <a-form :model="doc"
                :rules="rules"
                ref="myForm"
                @finish="handleOk"
        >
          <a-form-item label="名称" name="name">
            <a-input v-model:value="doc.name" placeholder="请输入文档名称" />
          </a-form-item>

          <a-form-item label="父文档" name="parent">
            <a-select
                v-model:value="doc.parent"
                show-search
                placeholder="请选择父文档"
                style="width: 200px"
                :options="searchOptions"
                :field-names="{ label: 'name', value: 'id'}"
                :filter-option="filterOption"
            ></a-select>

          </a-form-item>
          <a-form-item label="顺序" name="sort">
            <a-input v-model:value="doc.sort" placeholder="请输入文档顺序" />
          </a-form-item>
          <a-form-item >
            <a-button type="primary" @click="showDrawer">内容预览</a-button>
          </a-form-item>
          <a-form-item label="内容">
            <div style="border: 1px solid #ccc">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
            </div>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-form-item>
        </a-form>
      </a-row>
    </a-col>
  </a-row>

  <a-drawer
      v-model:visible="drawerVisible"
      width="640"
      class="custom-class"
      title="内容预览"
      placement="right"
  >
    <div v-html="doc.content"></div>
  </a-drawer>


</template>

<script>
import { SmileOutlined, DownOutlined,QuestionCircleOutlined } from '@ant-design/icons-vue';
import {ref, shallowRef} from "vue";
import { useRoute } from 'vue-router'
import axios from "axios";
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import {Form, message, Modal} from 'ant-design-vue';

const columns = [{
    dataIndex: 'name',
    key: 'name',
    title: "名称"
  }, , {
    title: '顺序',
    dataIndex: 'sort',
    key: 'sort',
  },  {
  title: '阅读数',
  dataIndex: 'viewCount',
  key: 'viewCount',
}, {
  title: '点赞数',
  dataIndex: 'voteCount',
  key: 'voteCount',
},{
    title: 'Action',
    key: 'action',
  }];


export default {
  name: "admin-doc",
  components: {
    SmileOutlined,
    DownOutlined,
    QuestionCircleOutlined,
    Editor, Toolbar
  },
  setup() {
    // 初始化表格
    const docs = ref([]);
    const searchOptions = ref([]);
    const loading = ref(true);

    const route = useRoute();

    // 路径中的参数
    // let ebookId = route.params.id;
    // 查询参数
    let ebookId = route.query.ebookId;
    const tableLoading = ref(false);

    // 获取表格数据
    const get = () => {
      tableLoading.value = true;
      const params = {
        ebookId: ebookId
      }

      if (searchValue.value){
        params.name = searchValue.value
      }
      axios.get("/doc/all", {params}).then( (res) => {
        let data = res.data;
        if (data.code == 200){

          tableLoading.value = false;

          docs.value = data.data;

          if (data.data){
            searchOptions.value = JSON.parse(JSON.stringify(data.data));
          } else{
            searchOptions.value = [];
          }

          searchOptions.value.unshift({name: '无', id: '0'});
          searchLoading.value = false;
        }
      });
    }

    // 新增
    const visible = ref(false);
    const title = ref('新增文档');
    const doc = ref({ebookId});
    const rules = {
      name: [{
        required: true,
        message: '请输入文档名称',
        trigger: 'blur'
      }],
      // 省略校验规则
    };;


    const add = () => {
        doc.value = {ebookId};
        const editor = editorRef.value
        if (editor == null) return
        editor.setHtml('');
    }

    const edit = (record) => {
      const obj = JSON.parse(JSON.stringify(record));
      if (!obj.content) {
        obj.content = '';
      }
      doc.value = obj;
      const editor = editorRef.value
      if (editor == null) return
      editor.setHtml(doc.value.content);
    }

    const handleOk = (e) => {
      const editor = editorRef.value
      if (editor == null) return;
      doc.value.content = editor.getHtml();
      axios.post('/doc', doc.value).then( (res) => {
          if (res.data.code == 200){
            let msg = "保存成功";
            if (doc.value.id){
              msg = "修改信息成功";
            }
            // 保存成功
            message.success(msg);

            // 表格数据的刷新， 回显
            get();

            // 清空表单数据
            doc.value = {};

            editor.setHtml('');
          } else {
            // 保存失败
            message.error(res.data.message);
          }
        visible.value = false;
      })
    }

    // 删除信息
    const remove = (id) => {

      function getNames(items){
        let names = [];
        items.forEach( (e) =>{
          if (e.id == id || e.parent == id){
            names.push(e.name);
          }
          if (e.children){
            names.push(...getNames(e.children));
          }
        })
        return names;
      };

      // 遍历所有文档
      let result = getNames(docs.value);

      Modal.confirm({
        title: '确认要删除【' + result + '】吗？',
        cancelText: '取消',
        okText: "确定",
        closable: true,
        onOk() {
          axios.delete('/doc/' + id).then((res) => {
            if (res.data.code == 200){
              message.success("删除成功");
              // 表格数据的刷新， 回显
              get();
            } else{
              message.error(res.data.message);
            }
          });
        },
        // content: 'some messages...some messages...',
      });
    }


    // 搜索
    const searchValue = ref("");
    const searchLoading = ref(false);

    const search = () =>{
      searchLoading.value = true;
      get();
    }

    const filterOption = (input, option) => {
      return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    // 富文本框
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    const mode =  ref('default') // 或 'simple';

    // 内容 HTML

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const drawerVisible = ref(false);

    const showDrawer = () =>{
      drawerVisible.value = true;
      const editor = editorRef.value
      if (editor == null) return;
      doc.value.content = editor.getHtml();
    }

    return {
      docs,
      columns,
      get,
      tableLoading,
      zhCN,
      title,
      add,
      doc,
      rules,
      handleOk,
      edit,
      remove,
      searchValue,
      searchLoading,
      search,
      filterOption,
      searchOptions,
      toolbarConfig,
      editorConfig,
      handleCreated,
      editorRef,
      mode,
      drawerVisible,
      showDrawer
    };
  },
  mounted() {
    this.get();
  }
}
</script>

<style scoped>
.cover{
  width: 80px;
  height: 80px;
}
</style>